//
//  EmoticonsAttachment.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/25.
//  Copyright (c) 2015年 bing. All rights reserved.
//


import UIKit

// MARK: - EmoticonsAttachment
class EmoticonsAttachment: NSTextAttachment {
    // 记录文字,使用
    var chs:String?
    
    // 将表情标记转换为属性文本
    func transformEmoticonsToAttributedString(emoticon: EmoticonModal, height: CGFloat) -> NSAttributedString{
        
        // 创建属性文本的附件
        let attachment = EmoticonsAttachment()
        attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
        
        // 设置属性文本高度
        attachment.bounds = CGRectMake(0, -4, height, height)
        attachment.chs = emoticon.chs
        
        // 获取属性文本
        let attrStr = NSAttributedString(attachment: attachment)
        
        return attrStr
    }
    
    
    // 我[爱你]是真的[嘻嘻],今天是愚人节[大小]!!!
    // 将一段带图片标示的的文字转换为属性文字
    func transformStringToAttributedString(str: String, height: CGFloat) -> NSAttributedString? {
        let pattern = "\\[(.*?)\\]"
        let regx = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)
        var attsM = NSMutableAttributedString(string: str)
        
        // 执行匹配,NSTextCheckingResult,匹配多个[AnyObject]
        if let results = regx?.matchesInString(str, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, count(str))) as? [NSTextCheckingResult]{
            
            // 获取属性对象
            let emoticons = EmoticonModal.emoticonsArray

            for (var i = results.count - 1;i >= 0; i--) {
                let range = results[i].rangeAtIndex(0)
                let emo = (str as NSString).substringWithRange(range)
                
                // 谓词
                let emoticon = emoticons.filter{$0.chs == emo}.last
                
                if emoticon != nil {
                    let picStr = self.transformEmoticonsToAttributedString(emoticon!, height: height)
                    attsM.replaceCharactersInRange(range, withAttributedString: picStr)
                }
            }
        }
        
        return attsM
    }
    
    
}